package com.team2.outpatient_sys.service.impl;

import com.team2.outpatient_sys.dao.PatientDao;
import com.team2.outpatient_sys.dao.UserDao;
import com.team2.outpatient_sys.pojo.Patient;
import com.team2.outpatient_sys.pojo.User;
import com.team2.outpatient_sys.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    @Autowired
    private PatientDao patientDao;

    @Override
    public User findById(int id) {
        return userDao.findById(id);
    }

    @Override
    public boolean add(User user) {
        return userDao.add(user) < 1 ? false : true;
    }

    @Override
    public boolean update(User user) {
        return userDao.update(user) < 1 ? false : true;
    }

    @Override
    public boolean bind(Patient patient, int userId) {
        int count = 0;
        Patient patient1 = patientDao.findByIdCard(patient.getIdCard());
        //如果绑定的病人已存在则直接从数据库中获取绑定，否则先添加病人再绑定
        if (patient1 == null) {
            String birth = patient.getIdCard().substring(6, 10) + "-" + patient.getIdCard().substring(10, 12) + "-" + patient.getIdCard().substring(12, 14);
            patient.setBirth(birth);
            int gender = Integer.parseInt(String.valueOf(patient.getIdCard().charAt(16)));
            if (gender % 2 == 0) {
                patient.setGender("女");
            } else {
                patient.setGender("男");
            }
            patientDao.add(patient);
            Integer patientId = patientDao.findByIdCard(patient.getIdCard()).getId();
            count = userDao.bind(userId, patientId);
        } else {
            count = userDao.bind(userId, patient1.getId());
        }
        return count < 1 ? false : true;
    }

    @Override
    public boolean unbind(int userId, int patientId) {
        return userDao.unbind(userId,patientId) < 1 ? false : true;
    }
}
